package com.monster.starter.core.filter;

import com.monster.common.Constant;
import com.monster.starter.core.common.config.CorsConfig;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 处理跨越请求
 * @author kuang
 */
@Component("monster-cors-filter")
@Order(Constant.FILTER_CORS_ORDER)
public class CorsFilter extends OncePerRequestFilter {
    /**
     * 跨域配置
     */
    @Resource
    private CorsConfig corsConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 跨域配置
        cors(response);
        // 拦截预请求
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            // 加入有跨域，跨域OPTIONS请求的时效性
            response.setHeader(HttpHeaders.ACCESS_CONTROL_MAX_AGE, corsConfig.getMaxAge());
        } else {
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 跨域配置
     * TODO: 目前是所有的网站都可以，以后要配置可以选择既定的域名和地址
     * @param response 响应对象
     */
    private void cors (HttpServletResponse response) {
        if (corsConfig.isOnOff()) {
            response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, corsConfig.getOrigin());
            response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, corsConfig.getMethods());
            response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, corsConfig.getAllowHeaders());
            response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, corsConfig.getExposeHeaders());
            response.setHeader("Access-Control-Allow-Credentials", "true");
        }
    }
}
